package controller

import (
	"context"
	"gin/common"
	"gin/model"
	"gin/response"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	o "github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/services/certificates"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
	"log"
	"os"
)

func WxJsapi(ctx *gin.Context) {
	Id := ctx.PostForm("orderId")
	if len(Id) == 0 {
		response.Fail(ctx, gin.H{}, "缺少订单标识")
		return
	}
	Db := common.GetDB()
	user, _ := ctx.Get("user")
	var orderInfo model.InsertOrder
	Db.Debug().Table("cat_meal_order").Where("uid=? and id=?", user.(model.UserInfo).Uid, Id).First(&orderInfo)
	if orderInfo.Id == 0 {
		response.Fail(ctx, gin.H{}, "订单错误")
		return
	}
	client := getClient()
	svc := jsapi.JsapiApiService{Client: client}
	// 得到prepay_id，以及调起支付所需的参数和签名
	resp, result, err := svc.PrepayWithRequestPayment(ctx, jsapi.PrepayRequest{
		Appid:       core.String(viper.GetString("wx.appid")),
		Mchid:       core.String(viper.GetString("wxpay.mchID")),
		Description: core.String(orderInfo.OrderNumber),
		OutTradeNo:  core.String(orderInfo.OrderNumber),
		Attach:      core.String(orderInfo.OrderNumber),
		NotifyUrl:   core.String("https://xcx2.6jiehui.com/beeorder/pay/notify"),
		Amount: &jsapi.Amount{
			Total: core.Int64(100),
		},
		Payer: &jsapi.Payer{
			Openid: core.String(user.(model.UserInfo).Openid),
		},
	},
	)
	log.Println(result)
	if err == nil {
		response.Success(ctx, gin.H{"pay": resp}, "success")
	} else {
		log.Println(err)
	}
}

func getClient() *core.Client {
	var (
		mchID                      = viper.GetString("wxpay.mchID")                      // 商户号
		mchCertificateSerialNumber = viper.GetString("wxpay.mchCertificateSerialNumber") // 商户证书序列号
		mchAPIv3Key                = viper.GetString("wxpay.mchAPIv3Key")                // 商户APIv3密钥
	)
	workDir, _ := os.Getwd()
	// 使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
	mchPrivateKey, err := utils.LoadPrivateKeyWithPath(workDir + "/cert/apiclient_key.pem")
	if err != nil {
		log.Fatal("load merchant private key error")
	}
	ctx := context.Background()
	// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	opts := []core.ClientOption{
		o.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		log.Fatalf("new wechat pay client err:%s", err)
	}

	// 发送请求，以下载微信支付平台证书为例
	// https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay5_1.shtml
	svc := certificates.CertificatesApiService{Client: client}
	resp, result, err := svc.DownloadCertificates(ctx)
	log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
	return client
}
